package com.gitee.huxing.course.netty.gateway.listener;

import com.gitee.huxing.course.netty.gateway.initializer.GateWayChannelInitializer;
import com.gitee.huxing.course.netty.listener.NettyListener;
import com.gitee.huxing.course.netty.util.IpAddressUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @Description: netty监听服务
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.netty.gateway.listener
 * @ClassName: NettyListener
 * @Author: huxing
 * @DateTime: 2021-08-19 下午1:06
 */
@Slf4j
public class NettyGateWayListener implements NettyListener {

    /** 端口号 **/
    private int port;

    /** 请求列表 **/
    private final List<String> proxyServers;

    /** 创建bootstrap **/
    private final ServerBootstrap serverBootstrap;

    /** 主线程 **/
    private  EventLoopGroup bossGroup;

    /** 工作线程 **/
    private  EventLoopGroup workerGroup;

    /** 默认网关名 **/
    public final static String GATEWAY_NAME = "NIOGateway";

    /** 默认网关版本号 **/
    public final static String GATEWAY_VERSION = "3.0.0";

    /**
     * @Description: 初始化监听服务
     * @Author: huxing
     * @param port          端口号
     * @param proxyServers  路由列表
     * @Date: 2021/8/19 下午4:27
     **/
    public NettyGateWayListener(int port, List<String> proxyServers) {
        this.port=port;
        this.proxyServers = proxyServers;
        this.serverBootstrap = new ServerBootstrap();
        this.bossGroup = new NioEventLoopGroup(4);
        this.workerGroup = new NioEventLoopGroup(100);
    }

    /**
     * @Description: 启动netty监听服务
     * @Author: huxing
     * @param
     * @Date: 2021/8/19 上午11:29
     **/
    @Override
    public void run() throws Exception {
        try {
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.SO_REUSEADDR, true)
                    .childOption(ChannelOption.SO_RCVBUF, 32 * 1024)
                    .childOption(ChannelOption.SO_SNDBUF, 32 * 1024)
//                    .childOption(EpollChannelOption.SO_REUSEPORT, true)
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(new GateWayChannelInitializer());
            log.info(GATEWAY_NAME + " " + GATEWAY_VERSION + "starting... {}", String.format("http://%s:%s/",
                    IpAddressUtil.getLocalHost(), port));
            // 绑定端口 - 启动服务监听
            Channel ch = serverBootstrap.bind(port).sync().channel();
            ch.closeFuture().sync();
        } finally {
            // 销毁所有资源
            destroy();
        }
    }

    /**
     * @Description: 关闭工作线程
     * @Author: huxing
     * @return java.lang.String
     * @Date: 2021/8/19 下午12:56
     **/
    private void destroy(){
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        log.info("Netty服务关闭，系统资源释放");
    }
}
